import axios from 'axios'
let state = {
    todos:[],
    count:1
}

let mutations = {
    getTodosSync(state,arr){
        state.todos = arr
    },
    addTodosSync(state,todo){
        state.todos.push(todo);
    },
    delSync(state,id){
        let index = state.todos.findIndex(item => item.id === id);
        state.todos.splice(index,1);
    },
    editSync(state,id){
        let index = state.todos.findIndex(item => item.id === id);
        state.todos[index].done = !state.todos[index].done;
    },
    toggleSync(state,checkAll){
        state.todos.forEach(item => {
            item.done = checkAll
        })
    }
}

let getters = {
    notDoneCount(state){
        return state.todos.filter(item => !item.done).length
    }
}

let actions = {
    getTodos({commit}){
        axios.get('/api/todos').then(res => {
            if(res.data.code === 1){
                commit('getTodosSync',res.data.data)
            }
        })
    },
    addTodos({commit},text){
        let id = new Date().getTime();
        axios.post('/api/add',{text,id,done:false}).then(res => {
            if(res.data.code === 1){
                commit('addTodosSync',{text,id,done:false})
            }
        })
    },
    del({commit},id){
        axios.get(`/api/del?id=${id}`).then(res => {
            console.log(id);
            if(res.data.code === 1){
                commit('delSync',id)
            }
        })
    },
    edit({commit},id){
        axios.get(`/api/edit?id=${id}`).then(res => {
            console.log(res);
            if(res.data.code === 1){
                commit('editSync',id);
            }
        })
    },
    toggleCheck({commit,state},checkAll){
        axios.get(`/api/toggle?done=${checkAll}`).then(res => {
            console.log(res);
            state.todos.forEach(item => {
                commit('toggleSync',checkAll)
            })
        })
    }
}

export default {
    state,
    mutations,
    actions,
    getters
}